package com.demo.threaddemo;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

public class CallableDemo {

	/**
	 * JDK 线程池
	 */
	static ExecutorService threads = Executors.newFixedThreadPool(10);
	
	public static void main(String[] args) {
		Callable<String> c1 = new Callable<String>() {
			@Override
			public String call() throws Exception {
				// 业务1
				return "业务1";
			}
		};

		Callable<String> c2 = new Callable<String>() {
			@Override
			public String call() throws Exception {
				// 业务2
				return "业务2";
			}
		};

		FutureTask<String> c1task = new FutureTask<String>(c1);
		FutureTask<String> c2task = new FutureTask<String>(c2);
		
//		test(c1task, c2task);
		test2(c1task, c2task);
		
	}
	
	public static <T> void test2(FutureTask<T> c1task, FutureTask<T> c2task){
		threads.submit(c1task);
		threads.submit(c2task);
		
		try {
			/*
			 * .get() 是阻塞，等 线程c1task执行完，可以get到值以后才会向下走
			 * 如果不阻塞的话，可以能获取不到值，会为空
			 */
			T c1Str = c1task.get();
			T c2Str = c2task.get();

			System.out.print(c1Str + "---------" + c2Str);
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}
	}
	
	public static <T> void test(FutureTask<T> c1task, FutureTask<T> c2task){
		new Thread(c1task).start();
		new Thread(c2task).start();

		try {
			/*
			 * .get() 是阻塞，等 线程c1task执行完，可以get到值以后才会向下走
			 * 如果不阻塞的话，可以能获取不到值，会为空
			 */
			T c1Str = c1task.get();  
			T c2Str = c2task.get();

			System.out.print(c1Str + "---------" + c2Str);
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}

	}

}
